package com.wisdom.weld.convert;

import com.google.common.base.CaseFormat;
import com.jayway.jsonpath.JsonPath;
import com.wisdom.weld.pojo.*;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class XMLObjectConverter {


    public static MapperXMLAttribute convert(TableAttribute tableAttribute) throws IOException {
        MapperXMLAttribute attribute = new MapperXMLAttribute();
        URL resource = ClassLoader.getSystemResource("generator.json");
        String basePackage = JsonPath.parse(new File(resource.getPath())).read("$.generator.base-package", String.class);
        List<ColumnAttribute> columnAttributes = tableAttribute.getColumnAttributes();
        List<String> columnList = columnAttributes.stream().map(ColumnAttribute::getColumnName).collect(Collectors.toList());
        attribute.setColumnList(columnList);
        columnAttributes.stream().filter(ColumnAttribute::getIsPrimaryKey).findFirst().ifPresent(attr -> attribute.setPrimaryKey(attr.getColumnName()));

        List<String> propertyList = columnAttributes.stream().map(attr -> CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, attr.getColumnName())).collect(Collectors.toList());
        attribute.setPropertyList(propertyList);

        String className = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableAttribute.getTableName());
        String entityFullName = String.format("%s.%s.%s", basePackage, "entity", className);
        attribute.setEntityFullName(entityFullName);

        String conditionFullName = String.format("%s.%s.%sCondition", basePackage, "condition", className);
        attribute.setConditionFullName(conditionFullName);

        String namespace = String.format("%s.%s.%s%s", basePackage, "mapper", className, "Mapper");
        attribute.setNamespace(namespace);
        attribute.setTableName(tableAttribute.getTableName());

        Map<String, String> columnPropertyMapping = new HashMap<>();
        for (ColumnAttribute columnAttribute : columnAttributes) {
            columnPropertyMapping.put(columnAttribute.getColumnName(), CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, columnAttribute.getColumnName()));
        }
        attribute.setColumnPropertyMapping(columnPropertyMapping);
        return attribute;
    }

    public static List<MapperXMLAttribute> convert(List<TableAttribute> tableAttributes) {
        List<MapperXMLAttribute> result = new ArrayList<>();
        try{
            for (TableAttribute tableAttribute : tableAttributes) {
                MapperXMLAttribute mapperXMLAttribute = convert(tableAttribute);
                result.add(mapperXMLAttribute);
            }
        } catch (IOException e){
            throw new RuntimeException("JSON PATH 读取数据异常", e);
        }
        return result;
    }


}
